package com.csf.controller;

import com.csf.annotation.intercpAnnotation;
import com.csf.dao.UserMapper;
import com.csf.entity.SessionReplace;
import com.csf.entity.User;
import com.csf.service.UserService;
import com.csf.service.likeService;
import com.csf.util.communityUtils;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/user")
public class UserController {

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private SessionReplace sessionReplace;

    @Autowired
    private likeService likeService;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

//    上传到七牛云的哪个内存空间
    @Value("${qiniu.header.name}")
    private String HeaderName;

    @Value("${qiniu.header.url}")
    private String HeaderUrl;

    @RequestMapping("/findUser/{id}")
    @ResponseBody
    public User findUser(@PathVariable("id") int id){
        User user = userMapper.findUserById(id);
        return user;
    }


//    获取设置头像的路径
    @intercpAnnotation
    @RequestMapping(path = "getSet",method = RequestMethod.GET)
    public String getSetting(){
////         进入setting界面之前，需要将设置的图片名和上传凭证获取到，然后统一带到setting页面
//        String fileName =communityUtils.getRandom();
////      如果上传成功，则返回响应信息（设置相应信息）
//        StringMap policy = new StringMap();
//        policy.put("returnBody",communityUtils.getJsonString(0));
////      生成上传凭证
//        Auth auth = Auth.create(accessKey,secretKey);
//        String upTicket = auth.uploadToken(HeaderName,fileName,3600,policy);
//
//        model.addAttribute("fileName",fileName);
//        model.addAttribute("upTicket",upTicket);
        return "/site/setting";
    }
//
////    更改数据库中的访问路径
//    @RequestMapping(path = "/updateUrls",method = RequestMethod.POST)
//    @ResponseBody
//    public String updateHeaderUrl(String fileName){
//        if (fileName == null){
//            return communityUtils.getJsonString(1,"图片名不能为空");
//        }
//        String url = HeaderUrl+"/"+fileName;
//        userMapper.updateHeader(sessionReplace.getUser().getId(),url);
//        return communityUtils.getJsonString(0);
//    }

//    图片存储的本地操作
//    跳转之后，进行图像操作
    @intercpAnnotation
    @RequestMapping(path = "/uploadImg",method = RequestMethod.POST)
    public String uploadHeader(MultipartFile imageFile, Model model){
        if (imageFile == null){
           model.addAttribute("erro","上传的文件有误");
           return "/site/setting";
        }
//        获取上传图片的文件名
        String filename = imageFile.getOriginalFilename();
//        设置文件名
        String substring = filename.substring(filename.lastIndexOf("."));
        if (substring == null){
            model.addAttribute("erro","图片格式有误，请重新上传");
            return "/site/setting";
        }
        //为了防止用户上传时头像的名字可能会一样造成冲突，所以我们需要利用工具将文件名更改
        String random = communityUtils.getRandom();
        filename = random + substring;
        //确定文件存放的位置
        File file = new File(uploadPath+"/"+filename);
        try {
//            上传
            imageFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        上传之后我们需要将图片在本地的路径存放进数据库中
        User user = sessionReplace.getUser();
        String HeaderUrl = domain+"/user/getImg/"+filename;
        userMapper.updateHeader(user.getId(),HeaderUrl);
        return "redirect:/discuss/findDis";
    }
    @intercpAnnotation
    @RequestMapping(value = "/getImg/{filename}",method = RequestMethod.GET)
    public void getHeaderImage(@PathVariable("filename") String filename, HttpServletResponse response){
          //图片存放路径
         filename =uploadPath +"/"+filename;
//         文件后缀
         String suffix = filename.substring(filename.lastIndexOf("."));
//        相应图片
         response.setContentType("image/"+suffix);
//
        FileInputStream fileInputStream =null;
        OutputStream outputStream =null;
        try {
            fileInputStream = new FileInputStream(filename);
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @intercpAnnotation
    @RequestMapping(value = "/alterpass",method = RequestMethod.POST)
    public String alterPassword(Model model,String oldPassword,String newPassword){
//        获取当前用户
        User user = sessionReplace.getUser();
        String password = user.getPassword();

//
        if (oldPassword == null){
            model.addAttribute("exceptold","原密码不能为空");
            return "/site/setting";
        }
        if (newPassword == null){
            model.addAttribute("exceptnew","新密码不能为空");
            return "/site/setting";
        }
        String old = communityUtils.mdFive(oldPassword+user.getSalt()).trim();
        if (!old.equals(password)){
            model.addAttribute("except","原密码错误，请重新输入");
            return "/site/setting";
        }

        String newPass = communityUtils.mdFive(newPassword+user.getSalt());
        userMapper.updatePassword(user.getId(), newPass);
        return "/site/login";
    }

    @RequestMapping(path = "/profile/{userId}",method = RequestMethod.GET)
    public String getProfile(@PathVariable("userId") int userId,Model model){
        User user = userService.findUserById(userId);
        if (user == null){
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("luser",user);
        int likeUserCount = likeService.likeUserCount(userId);
        model.addAttribute("likeUserCount",likeUserCount);

        return "/site/profile";
    }

}
